package com.ittx.dzt.baidu.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.baidu.handler.AbstractBaseBaiduApiHandler;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.OrderGetDTO;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.log.monitor.ExceptionLog;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 根据订单号下载订单详情
 * <p>
 * 查询订单详情 /PlatOrderBusinessQueryService/getOrderDetail
 * cy.salesOrder.download.byOrderId
 * https://dev2.baidu.com/content?sceneType=0&pageId=104168&nodeId=1139&subhead=
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/2/26
 */
@Slf4j
@Service
public class BaiduSalesOrderDownloadByIdService extends AbstractBaseBaiduApiHandler<OrderGetDTO> {

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SALESORDER_DOWNLOAD_BY_ORDERID;
	}

	@Override
	public String getBaiduMethod() {
		return "/PlatOrderBusinessQueryService/getOrderDetail";
	}

	@Override
	public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
		// 参数校验
		Result<?> result = checkParams(platformApiParamDTO, orderGetDTO);
		if (result.hasError()) {
			return result;
		}
		List<Object> list = new ArrayList<>();
		String[] orderCodeArr = orderGetDTO.getOrderId().split(",");
		if (orderCodeArr.length > 0) {
			for (String code : orderCodeArr) {
				result = this.getOrderById(platformApiParamDTO, code);
				if (result.hasError()) {
					return result;
				}
				Object resultData = result.getData();
				// 同步返回
				if (orderGetDTO.getIsAsync() == 0) {
					list.add(resultData);
				} else {
					platformApiParamDTO.setPlatformIdentifierTag(code);
					result = this.sendRequestToPlatform(platformApiParamDTO, resultData, true);
					if (!result.isSuccess()) {
						return result;
					}
				}
			}
		}
		// 同步返回
		if (orderGetDTO.getIsAsync() == 0) {
			return Result.success().addData(list).addMsg(platformApiParamDTO.getStoreConfig().getChainUniqueCode());
		}
		return Result.success();
	}


	/**
	 * 根据id获取订单
	 *
	 * @param platformApiParamDTO
	 * @param id
	 * @return
	 */
	public Result<?> getOrderById(PlatformApiParamDTO platformApiParamDTO, String id) {
		return this.getOrderBySdk(platformApiParamDTO, id);
	}

	/**
	 * 执行api请求
	 *
	 * @param platformApiParamDTO
	 * @param id
	 * @return 请求结果 resultMap.get(DATA_FIELD)
	 */
	public Result<?> getOrderBySdk(PlatformApiParamDTO platformApiParamDTO, String id) {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		//请求头
		try {
			Map<String, Object> extendMap = platformApiParamDTO.getExtendMap();
			String authUserName = MapUtil.getStr(extendMap, "authUserName", "");
			if (StrUtil.isEmpty(authUserName)) {
				return Result.error("授权用户名,不可为空,请在拓展参数中加入参数:{}", "authUserName");
			}
			Map<String, Object> headerMap = MapUtil.newHashMap();
			headerMap.put("accessToken", storeConfig.getSessionKey());
			headerMap.put("userName", authUserName);


			Map<String, Object> bodyMap = MapUtil.newHashMap();
			bodyMap.put("orderId", id);
			// 	取值范围：枚举值，列表如下// 5 - 综合电商// 269 - 本地生活// 100012 - 招财猫
			bodyMap.put("appId", "5");
			bodyMap.put("shopId", storeConfig.getStoreUniqueCode());

			Map<String, Object> requestMap = MapUtil.newHashMap();
			requestMap.put("header", headerMap);
			requestMap.put("body", bodyMap);

			Result<?> result = this.executeApi(storeConfig, requestMap, platformApiParamDTO.getRequestId());
			if (result.hasError()) {
				return result;
			}

			Map respMap = (Map) result.getData();
			Map respBodyMap = MapUtil.get(respMap, "body", Map.class);
			List dataList = MapUtil.get(respBodyMap, "data", List.class);
			if (CollUtil.isEmpty(dataList)) {
				String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0018_MSG, platformApiParamDTO.getRequestId(), id);
				log.error(msg);
				return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0018, msg));
			}
			return Result.success().addData(dataList.get(0));
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, platformApiParamDTO.getRequestId(), this.getPlatformCode(), platformApiParamDTO.getApi(), e.getMessage());
			log.error(msg);
			ExceptionLog.error(e, msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg));
		}
	}

	/**
	 * 参数校验
	 *
	 * @param platformApiParamDTO 平台请求参数
	 * @param orderGetDTO         接口请求参数
	 */
	public Result<?> checkParams(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
		if (orderGetDTO == null || platformApiParamDTO.getStoreConfig() == null || StrUtil.isBlank(orderGetDTO.getOrderId())) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0004_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), getLocalApiMethod(), orderGetDTO);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0004, msg));
		}
		return Result.success();
	}


}
